﻿var postPath = '/gdp';
var columns = [];
var editAction = false;
var title = '数据维护';
var parameters = {};
var baseParam = {};

var notyf = new Notyf();

$(function () {
    getPageBaseInfo();
    $('.close').on('click', function () {
        $('#editContent').modal('hide');
        var $formData = $('#formData');
        $formData.find('select').selectpicker('val', '');
        $formData[0].reset();
    });

    $(window).resize(function () {
        $('#tb_list').bootstrapTable('resetView', {
            height: $(window).outerHeight() - 150
        });
    });
});

// 获取页面基本信息
function getPageBaseInfo() {
    $.ajax({
        type: 'POST',
        url: postPath + '/system/sysPageBaseInfo/getPageBaseInfoByPageCode',
        async: false,
        data: {pagecode: GetQueryString('pageCode')},
        success: function (res) {
            if (res.success) {
                var data = res.data;
                $('#title').text(title);
                baseParam = {
                    serviceId: data.searchserviceid,
                    type: data.servicetype
                };
                if (res.data.enable === 1) {
                    generateButtons(data.editfunc, data.pageprimarykey, data.editserviceid);
                    generateForm(data.pagecode, data.editserviceid);
                    bindSubmit(data.editserviceid);
                }

                generateTableField(data.servicetype, data.searchserviceid);
                initTablePage(data.servicetype, data.searchserviceid);
                generateSearchButtons(data.searchserviceid);
            }
        }
    });
}

// 生成 列表列头
function generateTableField(servicetype, searchserviceid) {
    var showFiledUrl = postPath + '/system/sysPageDetailsInfo/' + (servicetype === 'singleTableServer' ? 'getAllShowFieldByServiceId' : 'getAllShowFieldExecSQLByServiceId');
    $.ajax({
        type: 'POST',
        url: showFiledUrl,
        async: false,
        data: {
            serviceId: searchserviceid,
            pageCode: GetQueryString('pageCode')
        },
        success: function (res) {
            if (res.success) {
                columns.push({
                    field: 'state', checkbox: true, align: 'center', valign: 'middle',
                    formatter: function (value, row, index) {
                        return '<label class="checkbox-mark"></label>'
                    }
                });
                $.each(res.data, function (i, item) {
                    var filedNameCn = item.dfnameCn || item.dfname;
                    if (item.isshow != 0) {
                        var columnTitle = {
                            field: item.dfname,
                            title: filedNameCn,
                            align: item.columnalign,
                            valign: 'middle'
                        };
                        if (item.columnwidth) columnTitle['width'] = item.columnwidth;
                        if (item.columnformat !== '') {
                            // 获取格式化函数
                            getSysFunc(item.columnformat, function (result) {
                                if (result.success) {
                                    var formatter = new Function('return ' + result.data.funcscript);
                                    columnTitle['formatter'] = formatter();
                                }
                            });
                        }
                        columns.push(columnTitle);
                    }
                });
            }
        }
    });
}

// 获取格式化函数
function getSysFunc(guid, func) {
    $.ajax({
        url: postPath + '/system/sysfunc/getSysFunctionByGuid?guid=' + guid,
        async: false,
        success: function (result) {
            func && func(result);
        }
    });
}

// 初始化列表
function initTablePage(servicetype, searchserviceid) {
    // 获取列表展示字段
    var domain = postPath + '/business/' + (servicetype === 'singleTableServer' ? 'singleServer/' : 'multipleServer/');
    var getColumnsUrl = domain + (servicetype === 'singleTableServer' ? 'isPading' : 'selectIsPaging');
    var getDataUrl = domain + (servicetype === 'singleTableServer' ? 'querySingleTB' : 'multipleTableServer');

    $.getJSON(getColumnsUrl, {serviceID: searchserviceid})
        .done(function (isPage) {
            bindTableColumns('tb_list', getDataUrl, columns, isPage, searchserviceid);
        })
        .error(function () {
            notyf.alert("获取数据失败!");
            return;
        });
}

// 绑定 Table 列表
function bindTableColumns(el, url, columns, isPage, serviceId) {
    $('#' + el)
        .bootstrapTable('destroy')
        .bootstrapTable({
            url: url,
            height: $(window).outerHeight() - 150,
            columns: columns,
            pagination: isPage,
            striped: true,
            cache: false,
            pageList: [20, 50, 100],
            pageSize: 20,
            toolbar: "#toolbar",
            showColumns: true,
            showRefresh: true,
            sidePagination: "server",
            undefinedText: '-',
            queryParams: function (pageReqeust) {
                var params = {
                    serviceID: serviceId,
                    pageNO: pageReqeust.offset / pageReqeust.limit + 1,
                    pageSize: pageReqeust.limit,
                    isPreview: "true"
                };
                var conQuery = {};
                $('#searchForm').serializeArray().map(function (item) {
                    conQuery[item.name] = item.value;
                });
                $.extend(params, {conQuery: JSON.stringify(conQuery)});
                return params
            },
            responseHandler: function (res) {
                if (isPage) {
                    return {
                        "total": res.data.total,//总页数
                        "rows": res.data.rows   //数据
                    };
                }
                return res.data.rows;
            },
            onPostBody: function () {
                var $selectAll = $('input[name="btSelectAll"]');
                if ($selectAll.next().length > 0) $selectAll.next().remove();
                $selectAll.after('<label class="checkbox-mark"></label>');
                $('label.checkbox-mark').on('click', function () {
                    $(this).prev().trigger('click');
                });
            }
        });
}

// 生成 button
function generateButtons(editfunc, pageprimarykey, serviceID) {
    var editButtons = editfunc ? editfunc.split(',') : [];
    var btnsHtml = '<div class="btn-group pull-right">';
    editButtons.map(function (value) {
        switch (value) {
            case '0':
                btnsHtml +=
                    '<button id="btnDelete" type="button" class="btn btn-default"><i class="fa fa-trash"></i>&ensp;删 除</button>&ensp;';
                break;
            case '1':
                btnsHtml +=
                    '<button id="btnAdd" type="button" class="btn btn-default"><i class="fa fa-plus"></i>&ensp;新 增</button>&ensp;';
                break;
            case '2':
                btnsHtml +=
                    '<button id="btnEdit" type="button" class="btn btn-default"><i class="fa fa-edit"></i>&ensp;修 改</button>&ensp;';
                break;
        }
    });
    btnsHtml += '</div>';
    $('#toolbar').append(btnsHtml);
    $('#btnDelete').on('click', function () {
        var row = $('#tb_list').bootstrapTable('getSelections');
        bootbox.confirm("是否删除该记录?", function (isConfirm) {
            if (isConfirm) {
                $.ajax({
                    url: '/business/singleEditServer/seletePrimaryKey?serviceID=' + serviceID,
                    type: 'get',
                    async: true,
                    success: function (result) {
                        var strId = '';
                        $.each(row, function (index, data) {
                            strId += data[result.data];
                            if (index !== row.length - 1) {
                                strId += ',';
                            }
                        });

                        if (strId) {
                            $.ajax({
                                url: '/business/singleEditServer/singleDel',
                                type: 'get',
                                async: false,
                                data: {serviceID: serviceID, primaryKeys: strId},
                                success: function (result) {
                                    if (result.data > 0) {
                                        $('#tb_list').bootstrapTable('refresh');
                                    }
                                    notyf.confirm(result.message);
                                }
                            });
                        }
                    }
                });
            }
        });
    });
    $('#btnAdd').on('click', function () {
        editAction = false;
        $('#editContent').modal('show');
    });
    $('#btnEdit').on('click', function () {
        var row = $('#tb_list').bootstrapTable('getSelections');

        if (!row || row.length === 0) {
            notyf.alert("请选择要修改的数据!");
            return;
        }else if(row.length > 1){
            notyf.alert("请选择一行!");
            return;
        }
        editAction = true;
        // 通过绑定主键赋值
        for (var key in row[0]) {
            if (parameters[key]) {
                parameters[key] = row[0][key];
            }
        }


        // for (var key in row[0]) {
        //    if ("CITY_ID"==key.toString())
        //         parameters[key] = row[0][key].trim();
        // }
        notyf.alert(JSON.stringify(parameters));


        $.ajax({
            url: '/business/singleEditServer/getDataByKey',
            type: 'get',
            async: false,
            data: {serviceID: serviceID, conQuery: JSON.stringify(parameters)},
            success: function (result) {
                if (result.data && result.data.length > 0) {
                    var data = result.data[0];
                    for (var key in data) {
                        var $el = $('#' + key);
                        if ($el.is('select')) {
                            $el.selectpicker('val', data[key]);
                        } else {
                            $el.val(data[key]);
                        }
                    }
                    // $('#title').text(title + '修改');
                    $('#editContent').modal('show');

                }
            },
            error: function () {
            }
        });
    });
}

// 生成表单
function generateForm(pagecode, editserviceid) {
    $ajaxHttp('sysPageDetailsInfo/getEditExecSQLByServiceId', {
        serviceId: editserviceid,
        pageCode: pagecode
    }, function (result) {
        $.each(result.data, function (index, data) {
            if (data.requirekey) {
                parameters[data.dfname] = data.requirekey;
            }
            var formHtml = '';
            if (data.isshow == 1) {
                formHtml += '<div class="form-group">';
                formHtml += '<label class="col-sm-2 control-label" for="' + data.dfname + '">' + data.dfnameCn + '</label>';
                formHtml += '<div class="col-sm-10" id="body-' + data.dfname + '"></div>';
                formHtml += '</div>';
                $('.modal-body').append(formHtml);
                component(data, $('#body-' + data.dfname));
            }
        });
    });
}

// 生成 条件查询
function generateSearchButtons(searchserviceid) {
    $.ajax({
        type: 'POST',
        url: postPath + '/system/sysPageDetailsInfo/getAllQueryFieldByServiceId',
        async: false,
        data: {
            serviceId: searchserviceid,
            pageCode: GetQueryString('pageCode')
        },
        success: function (res) {
            var $searchForm = $('#searchForm');
            if (res.success && res.data.length > 0) {
                res.data.map(function (data) {
                    var dfnameCn = data.dfnameCn ? data.dfnameCn : data.dfname;
                    $searchForm.append('&ensp;&ensp;<label style="margin-2left:10px;" for="' + data.dfname + '">' + dfnameCn + '：</label>');
                    component(data, $searchForm);
                });
                $searchForm.append('&ensp;&ensp;<button id="btn_search" type="button" class="btn btn-success" style="margin-right: 20px;">查 询</button>&ensp;&ensp;');

                // 查询数据
                $('#btn_search').on('click', function () {
                    $("#tb_list").bootstrapTable('refresh');
                });
            }
        }
    });
}

function component(data, $el) {
    var initData = data.initdata || '';
    switch (data.showtype) {
        case 0:// 文本框
            $el.append('<input type="text" value="' + initData + '" class="form-control" id="' + data.dfname + '" name="' + data.dfname + '" data-valid="' + data.validatevalue + '" />');
            break;
        case 1:// 时间选择
            var value = '';
            if (data.initdata) {
                getSysFunc(data.initdata, function (result) {
                    if (result.success) {
                        var func = new Function('return ' + result.data.funcscript)();
                        var params = [];
                        if (data.highlight !== '') {
                            var funcScript = data.highlight;
                            var theParams = funcScript.substring(funcScript.indexOf('(') + 1, funcScript.indexOf(')'));
                            params = theParams === '' ? [] : theParams.split(',');
                        }
                        value = func.apply(null, params);
                    }
                });
            }
            $el.append('<input type="text" class="form-control" readonly="readonly" data-date-format="yyyy-mm-dd HH:mm:ss" value="' + value + '" id="' + data.dfname + '" name="' + data.dfname + '"  />');
            $("#" + data.dfname + "").datetimepicker({
                language: 'zh-CN',
                autoclose: true,
                autoUpdateInput: true
            });
            break;
        case 2:// 下拉选择框
            var selectHtml = '<input type="text" style="display: none;" class="form-control"/><select id="' + data.dfname + '" name="' + data.dfname + '" class="selectpicker show-tick form-control" data-live-search="true">';
            selectHtml += '<option value="">请选择</option>';
            var reg = /^SELECT/ig;
            if (reg.test(initData)) {
                // 执行 SQL 语句查询
                $.ajax({
                    type: 'POST',
                    url: postPath + '/system/sysPageDetailsInfo/executeSQLByServiceId',
                    async: false,
                    data: $.extend(baseParam, {sql: initData}),
                    success: function (res) {
                        initData = res.success ? res.data : [];
                        fullArray(initData);
                        selectHtml += '</select>';
                        $el.append(selectHtml);
                        resizeSelect(data.dfname);
                    }
                });
            } else {
                initData = initData ? JSON.parse(initData) : [];
                fullArray(initData);
                selectHtml += '</select>';
                $el.append(selectHtml);
                resizeSelect(data.dfname);
            }

            // 填充下拉框数据
        function fullArray(initData) {
            $.each(initData, function (index, item) {
                selectHtml += '<option value="' + item.value + '">' + item.text + '</option>';
            });
        }

            // 重置选择框
        function resizeSelect(id) {
            var $select = $('#' + id);
            if ($select.parents('#searchForm').length > 0) {
                $select.selectpicker({width: $select.prev().outerWidth()});
            }
        }

            break;
    }
    return '';
}

function bindSubmit(editService) {
    $('#btn-save').on('click', function () {
        var data = {};
        $('#formData')
            .serializeArray()
            .map(function (item) {
                data[item.name] = item.value;
            });

        // 判断是添加还是修改操作
        var action = editAction ? 'singleUpdate' : 'singleAdd';
        $.ajax({
            url: '/business/singleEditServer/' + action,
            type: 'GET',
            async: false,
            data: {serviceID: editService, conQuery: JSON.stringify(data)},
            success: function (result) {
                console.log(result);
                if (result.data > 0) {
                    $('.close').trigger('click');
                    $('#tb_list').bootstrapTable('refresh');
                }
                notyf.confirm(result.message);
            }
        });
    });
}

function GetQueryString(name) {
    var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)');
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return unescape(r[2]);
    return null;
}

function $ajaxHttp(url, data, func, method) {
    method = method || 'GET';
    $.ajax({
        url: postPath + '/system/' + url,
        method: method,
        data: data,
        dataType: 'json'
    }).done(function (result) {
        func && func(result);
    });
}
